The improvements are seen below.
Since methods can be used many times with different data,
it is often worthwhile to have them check for errors.
You only have to write the additional code once,
and it might keep your program from crashing.
Here is the improved printRange()
:
class ArrayOps { . . . // print elements start through end void printRange ( int[] x, int start, int end ) { for ( int index=start; index <= end && index >= 0 && index < x.length; index++ ) System.out.print( x[index] + " " ); System.out.println(); } }
Here is the testing class with several calls to printRange():
class ArrayDemo { public static void main ( String[] args ) { ArrayOps operate = new ArrayOps(); int[] ar1 = { -20, 19, 1, 5, -1, 27, 19, 5 } ; System.out.println("Test A:"); operate.printRange( ar1, 0, 3); System.out.println("Test B:"); operate.printRange( ar1, -1, 4); System.out.println("Test C:"); operate.printRange( ar1, 1, 12); } }